/*
* 四川生学教育科技有限公司
* Copyright (c) 2015-2025 Founder Ltd. All Rights Reserved.
*
* This software is the confidential and proprietary information of
* Founder. You shall not disclose such Confidential Information
* and shall use it only in accordance with the terms of the agreements
* you entered into with Founder.
*
*/
package cn.demo.server;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author WUANG (wa@sxw.cn)
 * @description DcController
 * @date 2018/7/5 15:02
 * @slogon 站在巨人的肩膀上
 * @since 2.0.0
 */
@RestController
public class DcController {


    @Autowired
    RestTemplate restTemplate;
    @Autowired
    LoadBalancerClient loadBalancerClient;

    /**
     * @return
     * @see <a href="http://blog.didispace.com/spring-cloud-starter-dalston-2-1/">http://blog.didispace.com/spring-cloud-starter-dalston-2-1/</a>
     * 通过接口的调用可以看到loadBalancerClient一直在负载均衡选取demo-service的不同实例来调用
     */
    @GetMapping("/consumer/1")
    public String dc1() {
        ServiceInstance serviceInstance = loadBalancerClient.choose("demo-service");
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/dc";
        System.out.println(url);
        return restTemplate.getForObject(url, String.class);
    }

    @Autowired
    RestTemplate lbRestTemplate;

    /**
     * @return
     * @see <a href="http://blog.didispace.com/spring-cloud-starter-dalston-2-2/">http://blog.didispace.com/spring-cloud-starter-dalston-2-2/</a>
     * 通过接口的调用可以看到页面一直在负载均衡选取demo-service的不同实例来调用
     */
    @GetMapping("/consumer/2")
    public String dc2() {
        String services = lbRestTemplate.getForObject("http://demo-service/dc", String.class);
        return services;
    }

}